<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Ninex\Lib\Http\Traits\ResponseTrait;
use Symfony\Component\HttpFoundation\Response;

class ApiAppMiddleware
{
    use ResponseTrait;
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $token = $request->input('token') ? : $request->header('authorization') ;
        if(empty($token)){
            return $this->error('Token错误或已经失效',401 ,401);
        }
        $token = str_replace('Bearer ','',$token);
        if(!$realtoken = Cache::get($token)){
            return $this->error('Token错误或已经失效',401 ,401);
        }
        $request->headers->set('authorization','Bearer '.$realtoken);
        $app = auth()->guard('aiapp')->user();
        if(empty($app)){
            return $this->error('Token错误或已经失效',401 ,401);
        }
        return $next($request);
    }
}
